package mysql

import (
	"reward-server/forms/request"
	"reward-server/global"

	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type WishingWall struct {
	Id          int64  `gorm:"column:id;primary_key;AUTO_INCREMENT;NOT NULL;comment:'编号'" json:"id"`
	AccountAddr string `gorm:"type:varchar(50);not null;comment:'账户地址'" json:"account_addr"`
	Name        string `gorm:"type:varchar(50);not null;comment:'名称'" json:"name"`
	Image       string `gorm:"type:varchar(200);not null;default:'' " json:"image"`
	Description string `gorm:"type:varchar(255);not null;default:'';comment:'描述'" json:"description"`
	BaseModel
}

// IWishingWall接口定义了一个方法GetId，用于获取指定id的WishingWall对象
type IWishingWall interface {
	GetId(id int64) (data *WishingWall, err error)
	Insert(goods *WishingWall) (err error)
	GetList(req request.WishSearchReq) (res []*WishingWall, total int64, err error)
}

// NewWishingWall函数用于创建一个IWishingWall接口的实现对象
func NewWishingWall() IWishingWall {
	return &WishingWall{}
}

// GetId方法用于获取指定id的WishingWall对象
func (w *WishingWall) GetId(id int64) (data *WishingWall, err error) {

	// 声明一个WishingWall对象
	var model *WishingWall
	// 使用global.DB.Where方法查询数据库中id为指定值的WishingWall对象
	result := global.DB.Where("id= ?", id).First(&model)
	if result.RowsAffected == 0 {

		zap.S().Errorf("查询许愿信息不存在:查询id:%v", id)
		return nil, status.Errorf(codes.NotFound, "无记录")

	}
	return model, nil
}

// Insert 推送消息新增操作
func (w *WishingWall) Insert(req *WishingWall) (err error) {

	result := global.DB.Save(&req)
	if result.Error != nil {
		zap.S().Error("创建失败:%+v", result.Error)
		return status.Errorf(codes.InvalidArgument, "创建失败")
	}
	return nil
}

func (w *WishingWall) GetList(req request.WishSearchReq) (res []*WishingWall, total int64, err error) {

	var model []*WishingWall
	localDb := global.DB.Model(WishingWall{})

	id := req.Id // 商品
	if id != 0 {
		localDb = localDb.Where(WishingWall{Id: id})
	}

	name := req.Name
	if name != "" {
		localDb = localDb.Where(WishingWall{Name: name})
	}
	if req.AccountAddr != "" {
		localDb = localDb.Where(WishingWall{AccountAddr: req.AccountAddr})
	}
	var count int64
	localDb.Count(&count)

	pages := req.P
	if pages == 0 {
		pages = 1
	}

	pagePerNum := req.N
	if pagePerNum == 0 {
		pagePerNum = 10
	}

	result := localDb.Scopes(Paginate(pages, pagePerNum)).Order("id  desc").Find(&model)
	if result.Error != nil {
		return model, 0, status.Errorf(codes.Internal, result.Error.Error())
	}

	return model, count, nil

}
